/*
 * Created on 2004-5-23 To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */

package cn.com.yinhex.as.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.CharArrayReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//编译问题
//import com.sun.xml.internal.messaging.saaj.util.Base64;



/**
 * @author test To change the template for this generated type comment go to
 *         Window - Preferences - Java - Code Generation - Code and Comments
 */
public class StringUtil {
	public static String replaceAll(String str, String pattern, String to) {
		Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
		StringBuffer sb = new StringBuffer();
		Matcher m = null;
		for (m = p.matcher(str); m.find();) {
			m.appendReplacement(sb, to);
		}
		m.appendTail(sb);
		return sb.toString();
	}
	
	/**
	 * 将传进来的字符串的html标签删除
	 * 
	 * @param str
	 * @return
	 */
	public static String stripTags(String str) {
		try {
			// str = str.replaceAll("<\\p{Alnum}+?>", "");
			str = str.replaceAll("<[^>]*>", "");
			return str;
		} catch (Exception e) {
			return str;
		}
	}

	/**
	 * 将传进来的字符串的换行符替成 <br/>
	 * 
	 * @param str
	 * @return
	 */
	public static String nl2br(String str) {
		try {
			return str.replaceAll("\r\n", "<br>").replaceAll("\n", "<br>");
		} catch (Exception e) {
			return str;
		}
	}

	public static String br2nl(String str) {
		try {
			return replaceAll(str, "<br\\s*[^>]*>", "\n");
		} catch (Exception e) {
			// TODO: handle exception
			return str;
		}
	}

	public static boolean containCNWords(String body) {
		if (body == null) {
			return false;
		}
		for (int i = 0; i < body.length(); i++) {
			if (body.charAt(i) > 255) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 字符串查找
	 * 
	 * @param str
	 * @param s1
	 * @return
	 */
	public static final int find(String str, String s1) {
		int count = 0;
		int fromindex = -1;
		while ((fromindex = str.indexOf(s1, fromindex + 1)) > -1) {
			count++;
		}
		return count;
	}

	/**
	 * 得到某字符串的md5哈希
	 * 
	 * @param str
	 * @return
	 */
	public static String md5(String str) {
		return EncryptUtil.getMD5(str);
	}

	/**
	 * 将字符串str按splitlit切分，1.4已经有方法
	 * 
	 * @param str
	 * @param splitlit
	 * @return 一个数组
	 */
	public static ArrayList split(String str, String split) {
		ArrayList al = new ArrayList();
		int startindex = 0;
		int endindex = -1;
		int splitlength = split.length();
		int strlength = str.length();
		while ((endindex = str.indexOf(split, startindex)) > -1) {
			String result = str.substring(startindex, endindex);
			if (result.length() > 0) {
				al.add(result);
			}
			startindex = endindex + splitlength;
		}
		if (!str.endsWith(split)) {
			al.add(str.substring(startindex, strlength));
		}
		return al;
	}

	/**
	 * 转换html特殊字符为html码
	 * 
	 * @param str
	 * @return
	 */
	public static String htmlSpecialChars(String str) {
		try {
			if (str.trim() == null) {
				return "";
			}
			StringBuffer sb = new StringBuffer();
			char ch = ' ';
			for (int i = 0; i < str.length(); i++) {
				ch = str.charAt(i);
				if (ch == '&') {
					sb.append("&amp;");
				} else if (ch == '<') {
					sb.append("&lt;");
				} else if (ch == '>') {
					sb.append("&gt;");
				} else if (ch == '"') {
					sb.append("&quot;");
				} else if (ch == '\'') {
					sb.append("&#039;");
				} else if (ch == '(') {
					sb.append("&#040;");
				} else if (ch == ')') {
					sb.append("&#041;");
				} else if (ch == '@') {
					sb.append("&#064;");
				} else {
					sb.append(ch);
				}
			}
			if (sb.toString().replaceAll("&nbsp;", "").replaceAll("　", "").trim().length() == 0) {
				return "";
			}
			return sb.toString();
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 转换特殊字符
	 * 
	 * @param str
	 * @return
	 */
	public static String changeChar(String str) {
		try {
			if (str.trim() == null) {
				return "";
			}
			str = "_" + str;
			StringBuffer sb = new StringBuffer();
			char ch = ' ';
			for (int i = 0; i < str.length(); i++) {
				ch = str.charAt(i);
				if (ch == '#' && str.charAt(i - 1) == '-' && str.charAt(i + 1) == 'i') {
					sb.append("\\#");
				} else {
					sb.append(ch);
				}
			}
			return sb.toString().substring(1);
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * 删除字符串中的所有空格和换行
	 * 
	 * @param str
	 * @return
	 */
	public static String stripSpace(String str) {
		try {
			str = str.replaceAll("&nbsp;", "");
			str = str.replaceAll(" ", "");
			str = str.replaceAll("\r", "");
			str = str.replaceAll("\n", "");
			return str;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 在长数字前补零
	 * 
	 * @param num
	 *            数字
	 * @param length
	 *            输出位数
	 */
	public static String addzero(long num, int length) {
		String str = "";
		if (num < Math.pow(10, length - 1)) {
			for (int i = 0; i < (length - (num + "").length()); i++) {
				str += "0";
			}
		}
		str = str + num;
		return str;
	}

	/**
	 * 在数字前补零
	 * 
	 * @param num
	 *            数字
	 * @param length
	 *            输出位数
	 */
	public static String addzero(int num, int length) {
		String str = "";
		if (num < Math.pow(10, length - 1)) {
			for (int i = 0; i < (length - (num + "").length()); i++) {
				str += "0";
			}
		}
		str = str + num;
		return str;
	}

	/**
	 * 判断字符串是否一个数字
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNum(String str) {
		char[] cs = str.toCharArray();
		for (int i = 0; i < cs.length; i++) {
			if (cs[i] < 48 || cs[i] > 57) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 判断字符串是否正常
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isFine(String str) {
		if (str == null || str.trim().length() == 0) {
			return false;
		}
		return true;
	}

	public static boolean isFine(String str1, String str2) {
		if (isFine(str1) && isFine(str2)) {
			return true;
		}
		return false;
	}

	public static boolean isFine(String str1, String str2, String str3) {
		if (isFine(str1) && isFine(str2) && isFine(str3)) {
			return true;
		}
		return false;
	}

	/**
	 * 判断一组字符串是否都正常
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isFine(String[] str) {
		if (str == null) {
			return false;
		}
		for (int i = 0; i < str.length; i++) {
			if (!isFine(str[i])) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 检查关键字
	 * 
	 * @param words
	 * @param str
	 * @param tostr
	 * @return
	 */
	public static boolean haveWord(String[] words, String str) {
		for (int i = 0; i < words.length; i++) {
			if (str.indexOf(words[i]) > -1) {
				return true;
			}
		}
		return false;
	}

	/**
	 * s中的s1替换成s2
	 * 
	 * @param s
	 * @param s1
	 * @param s2
	 * @return
	 */
	public static final String replace(String s, String s1, String s2) {
		if (s == null)
			return null;
		int i = 0;
		if ((i = s.indexOf(s1, i)) >= 0) {
			char ac[] = s.toCharArray();
			char ac1[] = s2.toCharArray();
			int j = s1.length();
			StringBuffer sb = new StringBuffer(ac.length);
			sb.append(ac, 0, i).append(ac1);
			i += j;
			int k;
			for (k = i; (i = s.indexOf(s1, i)) > 0; k = i) {
				sb.append(ac, k, i - k).append(ac1);
				i += j;
			}
			sb.append(ac, k, ac.length - k);
			return sb.toString();
		} else {
			return s;
		}
	}

	/**
	 * 替换第一个出现的词语
	 * 
	 * @param str
	 * @param from
	 * @param to
	 * @return
	 */
	public static final String replaceFirst(String s, String s1, String s2) {
		int firstposition = s.indexOf(s1);
		if (firstposition == -1) {
			return s;
		}
		StringBuffer sb = new StringBuffer();
		sb.append(s.substring(0, firstposition));
		sb.append(s2);
		sb.append(s.substring(firstposition + s1.length()));
		return sb.toString();
	}
	
	/**
     * 判断是否为空
     * 
     * @param str
     * @return
     */
	public static final boolean isNull(String str) {
	    if(str!=null&&str.length()>0){
	        return false;
	    }else {
            return true;
        }
	}

	/**
	 * 得到后缀名
	 * 
	 * @param filename
	 * @return
	 */
	public static final String getExt(String filename) {
		int last_point_position = filename.lastIndexOf(".");
		int last_slash_position = filename.lastIndexOf("/");
		if (last_point_position > -1) {
			if ((last_slash_position > -1 && last_point_position > last_slash_position) || last_slash_position == -1) {
				String ext = filename.substring(last_point_position).toLowerCase();
				int q_pos = ext.indexOf("?");
				if (q_pos > 0) {
					return ext.substring(0, q_pos);
				}
				return ext;
			} else {
				return "";
			}
		}
		return "";
	}

	/**
	 * URL编码
	 * 
	 * @param str
	 * @return
	 */
	public static String URLEncode(String str) {
		try {
			return URLEncoder.encode(str, "GBK");
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * URL解码
	 * 
	 * @param str
	 * @return
	 */
	public static String URLDecode(String str) {
		try {
			return URLDecoder.decode(str, "GBK");
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * BASE64 编码
	 */
	public static String BASE64encode(String s) {
		try {
//		    编译不过，暂时注释
//			Base64.encode(s.getBytes("UTF-8"));
			return new String();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * BASE64 解码
	 */
	public static String BASE64decode(String s) {
//	    编译不过，暂时注释
//		return Base64.base64Decode(s);
	    return s;
	}

	/**
	 * 通用编码
	 * 
	 * @param s
	 * @return
	 */
	public static String Encode(String s) {
		try {
			s = URLEncoder.encode(s, "UTF-8");
			s = StringUtil.replace(s, "%", "_");
			return s;
		} catch (Exception e) {
			return s;
		}
	}

	/**
	 * 通用解码
	 * 
	 * @param s
	 * @return
	 */
	public static String Decode(String s) {
		try {
			s = StringUtil.replace(s, "_", "%");
			s = URLDecoder.decode(s, "UTF-8");
			return s;
		} catch (Exception e) {
			return s;
		}
	}

	/**
	 * 转换字符串成boolean值
	 * 
	 * @param s
	 * @return
	 */
	public static boolean toBoolean(String s) {
		if (s == null || s.length() == 0 || s.equals("false") || s.equals("0")) {
			return false;
		}
		return true;
	}

	/**
	 * 转换数字成boolean值
	 * 
	 * @param i
	 * @return
	 */
	public static boolean toBoolean(int i) {
		if (i <= 0) {
			return false;
		}
		return true;
	}

	/**
	 * 截取中文字符串
	 * 
	 * @param str
	 * @param start
	 * @param length
	 * @return
	 */
	public static String subString(String str, int start, int length) {
		try {
			if (str.getBytes("GBK").length <= length * 2) {
				return str;
			}
			if (length <= 0) {
				return "";
			}
			byte[] bytes = str.getBytes("GBK");
			int check = 1;
			for (int i = 0; i < start * 2; i++) {
				check = check * bytes[i];
				if (check > 1000) {
					check = 1;
				}
				if (check < -1000) {
					check = -1;
				}
			}
			if (check < 0 && bytes[start * 2] < 0) {
				start--;
			}
			byte[] newbytes = new byte[length * 2];
			check = 1;
			for (int i = 0; i < newbytes.length; i++) {
				newbytes[i] = bytes[start + i];
				check = check * bytes[start + i];
				if (check > 1000) {
					check = 1;
				}
				if (check < -1000) {
					check = -1;
				}
			}
			if (check < 0 && newbytes[newbytes.length - 1] < 0) {
				newbytes[newbytes.length - 1] = 32;
			}
			return new String(newbytes, "GBK");
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}

	public static final String subString(String str, int length) {
		try {
			byte[] bs = str.getBytes("GBK");
			if (bs.length < length * 2) {
				return str;
			}
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			int sign = 0;
			for (int i = 0; i < bs.length && i < length * 2; i++) {
				if (bs[i] < 0) {
					sign++;
				}
				if (i == length * 2 - 1) {
					if (sign % 2 == 0) {
						baos.write(bs[i]);
					}
				} else {
					baos.write(bs[i]);
				}
			}
			return new String(baos.toByteArray(), "GBK");
		} catch (Exception e) {
			return str;
		}
	}

	public static final String substring(String str, int start, int end) {
		if (str.getBytes().length < end) {
			return str;
		}
		return str.substring(start, end);
	}

	/**
	 * 
	 *得到全文搜索字符串
	 * 
	 */
	public static String getIntString(String str) {
		byte[] bytes = str.getBytes();
		StringBuffer sb = new StringBuffer();
		int iscn = 0;
		for (int i = 0; i < bytes.length; i++) {
			int j = bytes[i];
			if (bytes[i] < 0) {
				j = j * (-1);
				if (j < 10) {
					sb.append('0');
				}
				sb.append(j);
				iscn++;
				if (iscn == 2) {
					sb.append(' ');
					iscn = 0;
				}
			} else {
				sb.append(new String(new byte[] { bytes[i] }));
				if (i <= bytes.length - 2 && bytes[i + 1] < 0) {
					sb.append(' ');
				}
			}
		}
		return sb.toString();
	}

	public static String ruship(String ip) {
		try {
			return ip.substring(0, ip.lastIndexOf(".")) + ".*";
		} catch (Exception e) {
			return "";
		}
	}

	/*
	 * 限制字符串长度，html码除外
	 */
	static Pattern pcut = Pattern.compile(">([^<]*)<", Pattern.CASE_INSENSITIVE);

	public static String cutString(String str, int length) {
		try {
			if (str.getBytes("GBK").length < length * 2) {
				return str;
			}
			if (str.indexOf("<") < 0 || str.indexOf(">") < 0) {
				// System.out.println(length);
				return subString(str, length);
			}
			StringBuffer sb = new StringBuffer();
			Matcher m = pcut.matcher(str);
			int dylen = 0;
			while (m.find()) {
				// System.out.println("dylen:"+dylen);
				// System.out.println("length-dylen:"+(length-dylen));
				String s = m.group(1);
				m.appendReplacement(sb, ">" + subString(s, length - dylen) + "<");
				int thelen = s.getBytes("GBK").length;
				if (thelen % 2 == 1) {
					thelen = ((thelen + 1) / 2);
				} else {
					thelen = thelen / 2;
				}
				dylen += thelen;
			}
			m.appendTail(sb);
			str = sb.toString();
			return str;
		} catch (Exception e) {
			return "";
		}
	}

	public static String[] getImgUrls(String body) {
		Pattern PwgetImgs = Pattern.compile("<img.*?src\\=[\"' ]*([^\"' ]*)[\"' ]*.*?>", Pattern.CASE_INSENSITIVE);
		String aa = "";
		boolean isfind = false;
		try {
			Matcher m = PwgetImgs.matcher(body);
			while (m.find()) {
				isfind = true;
				aa += replace(m.group(1), "&amp;", "&") + "; ;";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		/*
		 * try { Matcher m = PwgetAs.matcher(body); while (m.find()) { String
		 * abc = m.group(2); if (abc.toLowerCase().endsWith(".jpg") ||
		 * abc.toLowerCase().endsWith(".gif") ||
		 * abc.toLowerCase().endsWith(".png") ||
		 * abc.toLowerCase().endsWith(".img")) { aa += abc + "; ;"; } } } catch
		 * (Exception e) { e.printStackTrace(); } if (aa.indexOf("; ;") < 0) {
		 * return null; }
		 */
		if (isfind) {
			return aa.split("; ;");
		}
		return null;
	}

	private static Pattern Pcheck = Pattern.compile("<([^>]*)>", Pattern.CASE_INSENSITIVE);

	private static Pattern PcheckScript = Pattern.compile("<script(.*?)</script\\s*>", Pattern.CASE_INSENSITIVE);

	public static String w3cRepair(String str) {
		str = str.replaceAll("\r\n", "[.ln.]").replaceAll("\n", "[.ln.]");
		try {
			StringBuffer sb = new StringBuffer();
			Matcher m = PcheckScript.matcher(str);
			while (m.find()) {
				m.appendReplacement(sb, "<SCRIPT" + m.group(1).replaceAll("<", "[script_tag]") + "</SCRIPT>");
			}
			m.appendTail(sb);
			str = sb.toString();
		} catch (Exception e) {
		}
		try {
			StringBuffer sb = new StringBuffer();
			Matcher m = Pcheck.matcher(str);
			while (m.find()) {
				String g1 = "";
				String[] g1s = m.group(1).replaceAll("\"", "").split(" ");
				for (int i = 0; i < g1s.length; i++) {
					g1 += " ";
					if (g1s[i].indexOf("=") > 0) {
						g1 += g1s[i].substring(0, g1s[i].indexOf("="));
						g1 += "=";
						g1 += "\"";
						g1 += g1s[i].substring(g1s[i].indexOf("=") + 1, g1s[i].length());
						g1 += "\"";
					} else {
						g1 += g1s[i];
					}
				}
				m.appendReplacement(sb, "<" + g1.trim() + ">");
			}
			m.appendTail(sb);
			str = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		str = str.replaceAll("<(br|BR)\\s*>", "<BR />");
		str = str.replaceAll("<(img|IMG)([^>]*)>", "<IMG$2 />");
		str = str.replaceAll("\\[.ln.\\]", "\n");
		str = str.replaceAll("\\[script_tag\\]", "<");
		return str;
	}

	/**
	 * 过滤`字符
	 * 
	 * @param str
	 * @return
	 */
	public static final String rejectSQLinjection(String str) {
		return str.replace('`', '\'').replace(' ', '\'');
	}

	/**
	 * 得到所有链接
	 * 
	 * @param str
	 * @return
	 */

	public static ArrayList getALink(String html) {
		return HTMLUtil.getALink(html);
	}

	public static String strip63(String str) {
		try {
			byte[] bs = str.getBytes();
			java.nio.ByteBuffer bb = java.nio.ByteBuffer.allocate(bs.length * 4);
			for (int ii = 0; ii < bs.length; ii++) {
				if (bs[ii] == 63) {
					bb.putInt(32);
					continue;
				}
				bb.putInt(bs[ii]);
			}
			byte[] bbbs = bb.array();
			for (int ii = 0; ii < bs.length; ii++) {
				bs[ii] = bbbs[ii * 4 + 3];
			}
			return new String(bs);
		} catch (Exception e) {
			return str;
		}
	}

	public static final boolean greatThen(String a, String b) {
		int alen = a.length();
		int blen = b.length();
		int minlen = Math.min(alen, blen);
		char[] achars = a.toCharArray();
		char[] bchars = b.toCharArray();
		for (int i = 0; i < minlen; i++) {
			if (achars[i] > bchars[i]) {
				return true;
			}
		}
		return false;
	}

	public static final boolean lessThen(String a, String b) {
		int alen = a.length();
		int blen = b.length();
		int minlen = Math.min(alen, blen);
		char[] achars = a.toCharArray();
		char[] bchars = b.toCharArray();
		for (int i = 0; i < minlen; i++) {
			if (achars[i] < bchars[i]) {
				return true;
			}
		}
		return false;
	}

	public static String fcEncode(String str) {
		try {
			byte[] cs = str.getBytes("UTF-8");
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < cs.length; i++) {
				String c16 = (cs[i]) < 0 ? IntUtil.c10to16(256 + (cs[i])) : IntUtil.c10to16(cs[i]);
				sb.append("%");
				sb.append(c16);
			}
			return sb.toString();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
	}

	public static String fcDecode(String str) {
		try {
			return java.net.URLDecoder.decode(str, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}

	public static String reverse(String str) {
		if (str == null)
			return null;
		StringBuffer sb = new StringBuffer();
		char[] cs = str.toCharArray();
		for (int i = cs.length - 1; i >= 0; i--) {
			sb.append(cs[i]);
		}
		return sb.toString();
	}

	public static String grepA(String str, String s, int lines) {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new CharArrayReader(str.toCharArray()));
			String line = "";
			StringBuffer sb = new StringBuffer();
			boolean start = false;
			int i = 0;
			while ((line = reader.readLine()) != null && i < lines) {
				if (start) {
					sb.append(line);
					sb.append("\n");
					i += 1;
				}
				if (line.indexOf(s) > -1) {
					start = true;
				}
			}
			reader.close();
			return sb.toString();
		} catch (Exception e) {
			return "";
		} finally {
			try {
				reader.close();
				reader = null;
			} catch (Exception e2) {
			}
		}
	}

	public static String grep(String str, String s) {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new CharArrayReader(str.toCharArray()));
			String line = "";
			while ((line = reader.readLine()) != null) {
				if (line.indexOf(s) > -1)
					return line;
			}
			return "";
		} catch (Exception e) {
			return "";
		} finally {
			try {
				reader.close();
				reader = null;
			} catch (Exception e2) {
			}
		}
	}
    
    public static String m2g(long l){
        String str = String.valueOf(l);
        if(str.length()<9){
            for(int i= 0;i<=9-str.length();){
                str = "0"+str;
                
            }
        }
        
         return str;
        
    }
    

    /**
     * 使HTML的标签失去作用*
     * 
     * @param input
     *            被操作的字符串
     * @return String
     */
    public static final String escapeHTMLTag(String input) {
        if (input == null)
            return "";
        input = input.trim().replaceAll("&", "&amp;");
        input = input.replaceAll("<", "&lt;");
        input = input.replaceAll(">", "&gt;");
        input = input.replaceAll("\n", "<br>");
        input = input.replaceAll("'", "&#39;");
        input = input.replaceAll("\"", "&quot;");
        input = input.replaceAll("\\\\", "&#92;");
        return input;
    }
    
    /**
     * 还原html标签
     * @param input
     * @return
     */
    public static final String unEscapeHTMLTag(String input) {
        if (input == null)
          return "";
        input = input.trim().replaceAll("&amp;", "&");
        input = input.replaceAll("&lt;", "<");
        input = input.replaceAll("&gt;", ">");
        input = input.replaceAll("<br>", "\n");
        input = input.replaceAll("&#39;", "'");
        input = input.replaceAll("&quot;", "\"");
        input = input.replaceAll("&#92;", "\\\\");
        return input;
      }
	
}
